// 应用主要JavaScript逻辑
class ArticleSyncApp {
    constructor() {
        this.selectedPlatforms = new Set();
        this.currentFile = null;
        this.platforms = [];
        this.articles = [];
        this.videos = [];
        this.isPublishing = false; // 添加发布状态标记
        
        this.init();
    }
    
    init() {
        // 确保DOM完全加载后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.setupEventListeners();
                this.setupGlobalKeyboardHandlers();
                this.loadPlatforms();
                this.showSection('upload');
            });
        } else {
            this.setupEventListeners();
            this.setupGlobalKeyboardHandlers();
            this.loadPlatforms();
            this.showSection('upload');
        }
    }
    
    // 设置全局键盘事件处理器
    setupGlobalKeyboardHandlers() {
        // 全局键盘事件处理，确保在模态框中也能正常使用快捷键
        document.addEventListener('keydown', (e) => {
            // 检查是否是粘贴快捷键 (Ctrl+V 或 Cmd+V)
            if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
                const activeElement = document.activeElement;
                
                // 如果当前焦点在我们的文本框中，确保事件不被拦截
                if (activeElement && (
                    activeElement.tagName === 'TEXTAREA' || 
                    (activeElement.tagName === 'INPUT' && activeElement.type === 'text')
                )) {
                    // 阻止事件冒泡，但允许默认行为
                    e.stopPropagation();
                    console.log('粘贴快捷键检测到，目标元素:', activeElement.id);
                }
            }
        }, true); // 使用捕获阶段确保优先处理
        
        console.log('全局键盘事件处理器已设置');
    }
    
    // 设置事件监听器
    setupEventListeners() {
        // 导航菜单
        document.querySelectorAll('.sidebar .nav-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const section = e.target.closest('a').dataset.section;
                this.showSection(section);
            });
        });
        
        // 文件上传
        this.setupFileUpload();
        
        // 封面图片预览
        this.handleCoverImagePreview();
        
        // 文档预览和编辑
        this.setupDocumentPreviewAndEdit();
        
        // 在线编辑器
        this.setupDocumentEditor();
        
        // 表单提交
        this.setupForms();
        
        // 搜索功能
        this.setupSearch();
    }
    
    // 显示指定区域
    showSection(sectionName) {
        // 隐藏所有区域
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
        });
        
        // 移除所有导航链接的active状态
        document.querySelectorAll('.sidebar .nav-link').forEach(link => {
            link.classList.remove('active');
        });
        
        // 显示指定区域
        const targetSection = document.getElementById(sectionName + '-section');
        if (targetSection) {
            targetSection.classList.add('active');
        }
        
        // 激活对应的导航链接
        const targetLink = document.querySelector(`[data-section="${sectionName}"]`);
        if (targetLink) {
            targetLink.classList.add('active');
        }
        
        // 更新页面标题
        const titles = {
            upload: '内容上传',
            articles: '文章管理',
            videos: '视频管理',
            platforms: '平台管理',
            settings: '系统设置'
        };
        document.getElementById('page-title').textContent = titles[sectionName] || '内容上传';
        
        // 加载相应数据
        this.loadSectionData(sectionName);
    }
    
    // 加载区域数据
    loadSectionData(sectionName) {
        switch (sectionName) {
            case 'articles':
                this.loadArticles();
                break;
            case 'videos':
                this.loadVideos();
                break;
            case 'platforms':
                this.loadPlatformConfig();
                break;
        }
    }
    
    // 设置文件上传
    setupFileUpload() {
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        
        // 点击上传区域
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 文件选择
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleFileSelect(file);
            }
        });
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.handleFileSelect(files[0]);
            }
        });
        
        // 发布按钮
        document.getElementById('publish-btn').addEventListener('click', () => {
            this.publishContent();
        });
    }
    
    // 处理文件选择
    handleFileSelect(file) {
        this.currentFile = file;
        
        // 显示文件信息
        const fileInfo = document.getElementById('file-info');
        const fileDetails = document.getElementById('file-details');
        const documentActions = document.getElementById('document-actions');
        
        const fileType = this.getFileType(file.name);
        const fileSize = this.formatFileSize(file.size);
        
        fileDetails.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="fas ${this.getFileIcon(fileType)} fa-2x me-3 text-primary"></i>
                <div>
                    <h6 class="mb-1">${file.name}</h6>
                    <small class="text-muted">类型: ${fileType} | 大小: ${fileSize}</small>
                </div>
            </div>
        `;
        
        fileInfo.classList.remove('d-none');
        
        // 如果是Markdown文件，显示预览和编辑按钮
        if (this.isMarkdownFile(file.name)) {
            documentActions.classList.remove('d-none');
            console.log('检测到Markdown文件，显示预览和编辑按钮');
        } else {
            documentActions.classList.add('d-none');
        }
        
        // 自动填充标题
        const titleInput = document.getElementById('content-title');
        if (!titleInput.value) {
            titleInput.value = file.name.replace(/\.[^/.]+$/, "");
        }
    }
    
    // 获取文件类型
    getFileType(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        const types = {
            'md': 'Markdown文档',
            'mp4': '视频文件',
            'avi': '视频文件',
            'mov': '视频文件',
            'wmv': '视频文件',
            'flv': '视频文件',
            'mkv': '视频文件',
            'webm': '视频文件'
        };
        return types[ext] || '未知文件';
    }
    
    // 获取文件图标
    getFileIcon(fileType) {
        if (fileType.includes('文档')) {
            return 'fa-file-alt';
        } else if (fileType.includes('视频')) {
            return 'fa-video';
        }
        return 'fa-file';
    }
    
    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 加载平台列表
    async loadPlatforms() {
        try {
            const response = await fetch('/api/platforms');
            this.platforms = await response.json();
            await this.renderPlatforms();
            
            // 同时更新认证表单中的平台选择器
            this.updateAuthPlatformSelect();
            
        } catch (error) {
            console.error('加载平台列表失败:', error);
            this.showAlert('加载平台列表失败', 'danger');
        }
    }
    
    // 更新认证表单中的平台选择器
    updateAuthPlatformSelect() {
        const authPlatformSelect = document.getElementById('auth-platform');
        if (authPlatformSelect) {
            // 清空现有选项，保留默认选项
            authPlatformSelect.innerHTML = '<option value="">选择平台</option>';
            
            // 添加平台选项
            this.platforms.forEach(platform => {
                const option = document.createElement('option');
                option.value = platform.id;
                option.textContent = platform.name;
                authPlatformSelect.appendChild(option);
            });
        }
    }
    
    // 渲染平台列表
    async renderPlatforms() {
        const platformsList = document.getElementById('platforms-list');
        
        // 获取平台认证状态
        const platformsWithAuth = await Promise.all(
            this.platforms.map(async (platform) => {
                try {
                    const response = await fetch(`/api/platforms/${platform.id}/auth`);
                    const authList = await response.json();
                    return {
                        ...platform,
                        hasAuth: authList && authList.length > 0
                    };
                } catch (error) {
                    return {
                        ...platform,
                        hasAuth: false
                    };
                }
            })
        );
        
        platformsList.innerHTML = platformsWithAuth.map(platform => `
            <div class="platform-card border rounded p-3 mb-2 ${!platform.hasAuth ? 'border-warning' : ''}" data-platform-id="${platform.id}">
                <div class="d-flex align-items-center">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="${platform.id}" 
                               id="platform-${platform.id}" ${!platform.hasAuth ? 'disabled' : ''}>
                        <label class="form-check-label ms-2" for="platform-${platform.id}">
                            <div class="d-flex justify-content-between align-items-center w-100">
                                <div>
                                    <strong>${platform.name}</strong>
                                    <br>
                                    <small class="text-muted">支持: ${platform.supportedTypes}</small>
                                </div>
                                <div class="text-end">
                                    <span class="badge ${platform.hasAuth ? 'bg-success' : 'bg-warning'}">
                                        ${platform.hasAuth ? '已认证' : '未认证'}
                                    </span>
                                    ${!platform.hasAuth ? '<br><small class="text-warning">需要配置认证</small>' : ''}
                                </div>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
        `).join('');
        
        // 绑定平台选择事件
        platformsList.addEventListener('change', (e) => {
            if (e.target.type === 'checkbox') {
                const platformId = parseInt(e.target.value);
                const card = e.target.closest('.platform-card');
                
                if (e.target.checked) {
                    this.selectedPlatforms.add(platformId);
                    card.classList.add('selected');
                } else {
                    this.selectedPlatforms.delete(platformId);
                    card.classList.remove('selected');
                }
            }
        });
        
        // 显示认证提示
        const unauthenticatedCount = platformsWithAuth.filter(p => !p.hasAuth).length;
        const authTip = document.getElementById('auth-tip');
        if (authTip) {
            if (unauthenticatedCount > 0) {
                authTip.style.display = 'block';
            } else {
                authTip.style.display = 'none';
            }
        }
    }
    
    // 发布内容
    async publishContent() {
        console.log('开始发布内容流程');
        
        // 防止重复提交
        if (this.isPublishing) {
            this.showAlert('正在发布中，请勿重复提交', 'warning');
            return;
        }
        
        if (!this.currentFile) {
            console.log('用户未选择文件');
            this.showAlert('请先选择要上传的文件', 'warning');
            return;
        }
        
        if (this.selectedPlatforms.size === 0) {
            console.log('用户未选择发布平台');
            this.showAlert('请至少选择一个发布平台', 'warning');
            return;
        }
        
        console.log('开始执行认证检查');
        // 检查选中平台的认证状态
        const authCheckResult = await this.checkPlatformAuth();
        if (!authCheckResult.success) {
            console.log('认证检查失败，显示认证对话框');
            this.showAuthRequiredDialog(authCheckResult.unauthenticatedPlatforms);
            return;
        }
        
        console.log('认证检查通过，继续发布流程');
        
        // 设置发布状态
        this.isPublishing = true;
        this.updatePublishButton(true);
        
        const formData = new FormData();
        formData.append('file', this.currentFile);
        formData.append('title', document.getElementById('content-title').value);
        formData.append('tags', document.getElementById('content-tags').value);
        formData.append('isOriginal', document.getElementById('is-original').checked);
        formData.append('joinActivity', document.getElementById('join-activity').checked);
        
        const description = document.getElementById('content-description').value;
        if (description) {
            formData.append('description', description);
        }
        
        // 处理封面图片
        const coverImageInput = document.getElementById('cover-image');
        if (coverImageInput && coverImageInput.dataset.uploadedPath) {
            // 使用已上传的图片路径
            console.log('使用已上传的封面图片路径:', coverImageInput.dataset.uploadedPath);
            formData.append('coverImage', coverImageInput.dataset.uploadedPath);
        } else if (coverImageInput && coverImageInput.files.length > 0) {
            // 如果有文件但没有上传，先上传
            console.log('检测到新的封面图片文件，需要先上传:', coverImageInput.files[0].name);
            try {
                const uploadResult = await this.uploadImage(coverImageInput.files[0], 'covers');
                if (uploadResult.success) {
                    formData.append('coverImage', uploadResult.path);
                    console.log('封面图片临时上传成功:', uploadResult.path);
                } else {
                    console.warn('封面图片上传失败，将不使用封面图片:', uploadResult.error);
                }
            } catch (error) {
                console.warn('封面图片上传异常，将不使用封面图片:', error);
            }
        } else {
            console.log('未选择封面图片');
        }
        
        // 定时发布时间
        const scheduledTime = document.getElementById('scheduled-time').value;
        if (scheduledTime) {
            formData.append('scheduledTime', scheduledTime);
        }
        
        try {
            this.showPublishProgress();
            
            // 上传文件
            const fileType = this.getFileType(this.currentFile.name);
            const uploadUrl = fileType.includes('视频') ? '/api/videos/upload' : '/api/articles/upload';
            
            const uploadResponse = await fetch(uploadUrl, {
                method: 'POST',
                body: formData
            });
            
            if (!uploadResponse.ok) {
                throw new Error('文件上传失败');
            }
            
            const content = await uploadResponse.json();
            
            // 发布到平台
            const publishUrl = fileType.includes('视频') 
                ? `/api/videos/${content.id}/publish` 
                : `/api/articles/${content.id}/publish`;
            
            const publishData = new URLSearchParams();
            this.selectedPlatforms.forEach(platformId => {
                publishData.append('platformIds', platformId);
            });
            
            const publishResponse = await fetch(publishUrl, {
                method: 'POST',
                body: publishData
            });
            
            if (!publishResponse.ok) {
                throw new Error('发布失败');
            }
            
            this.showAlert('内容发布成功！', 'success');
            this.resetForm();
            
        } catch (error) {
            console.error('发布失败:', error);
            this.showAlert('发布失败: ' + error.message, 'danger');
        } finally {
            // 重置发布状态
            this.isPublishing = false;
            this.updatePublishButton(false);
            this.hidePublishProgress();
        }
    }
    
    /**
     * 上传图片文件到服务器
     * @param {File} imageFile - 图片文件
     * @param {string} category - 图片分类，默认为'covers'
     * @returns {Promise<Object>} 上传结果
     */
    async uploadImage(imageFile, category = 'covers') {
        try {
            console.log('开始上传图片:', imageFile.name, '分类:', category);
            
            const formData = new FormData();
            formData.append('file', imageFile);
            
            const uploadUrl = category === 'thumbnail' ? '/api/upload/thumbnail' : '/api/upload/image';
            
            const response = await fetch(uploadUrl, {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`上传失败: HTTP ${response.status}`);
            }
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.message || '上传失败');
            }
            
            console.log('图片上传成功:', result);
            return {
                success: true,
                path: result.path,
                url: result.url,
                fileName: result.fileName,
                fileSize: result.fileSize
            };
            
        } catch (error) {
            console.error('图片上传失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }
    
    /**
     * 处理封面图片上传预览
     */
    handleCoverImagePreview() {
        const coverImageInput = document.getElementById('cover-image');
        if (!coverImageInput) return;
        
        coverImageInput.addEventListener('change', async (event) => {
            const file = event.target.files[0];
            if (!file) return;
            
            console.log('用户选择了封面图片:', file.name);
            
            // 创建预览区域
            let previewContainer = document.getElementById('cover-preview-container');
            if (!previewContainer) {
                previewContainer = document.createElement('div');
                previewContainer.id = 'cover-preview-container';
                previewContainer.className = 'mt-2';
                coverImageInput.parentNode.appendChild(previewContainer);
            }
            
            // 显示加载状态
            previewContainer.innerHTML = `
                <div class="d-flex align-items-center text-muted">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    <small>正在上传封面图片...</small>
                </div>
            `;
            
            try {
                // 立即上传图片
                const uploadResult = await this.uploadImage(file, 'covers');
                
                if (uploadResult.success) {
                    // 显示预览
                    previewContainer.innerHTML = `
                        <div class="card" style="max-width: 200px;">
                            <img src="${uploadResult.url}" class="card-img-top" alt="封面预览" style="max-height: 120px; object-fit: cover;">
                            <div class="card-body p-2">
                                <small class="text-muted">
                                    <i class="fas fa-check-circle text-success me-1"></i>
                                    上传成功
                                </small>
                                <button type="button" class="btn btn-sm btn-outline-danger float-end" onclick="app.removeCoverImage()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    `;
                    
                    // 保存上传后的路径信息
                    coverImageInput.dataset.uploadedPath = uploadResult.path;
                    coverImageInput.dataset.uploadedUrl = uploadResult.url;
                    
                    console.log('封面图片上传成功，路径:', uploadResult.path);
                } else {
                    throw new Error(uploadResult.error);
                }
            } catch (error) {
                console.error('封面图片上传失败:', error);
                previewContainer.innerHTML = `
                    <div class="alert alert-danger alert-sm mb-0">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        <small>上传失败: ${error.message}</small>
                    </div>
                `;
                
                // 清空文件输入
                coverImageInput.value = '';
                delete coverImageInput.dataset.uploadedPath;
                delete coverImageInput.dataset.uploadedUrl;
            }
        });
    }
    
    /**
     * 移除封面图片
     */
    removeCoverImage() {
        const coverImageInput = document.getElementById('cover-image');
        const previewContainer = document.getElementById('cover-preview-container');
        
        if (coverImageInput) {
            coverImageInput.value = '';
            delete coverImageInput.dataset.uploadedPath;
            delete coverImageInput.dataset.uploadedUrl;
        }
        
        if (previewContainer) {
            previewContainer.innerHTML = '';
        }
        
        console.log('封面图片已移除');
    }
    async checkPlatformAuth() {
        console.log('开始检查平台认证状态，选中的平台:', Array.from(this.selectedPlatforms));
        const unauthenticatedPlatforms = [];
        
        for (const platformId of this.selectedPlatforms) {
            const platform = this.platforms.find(p => p.id === platformId);
            if (!platform) {
                console.warn(`未找到平台ID ${platformId} 对应的平台信息`);
                continue;
            }
            
            console.log(`检查平台 ${platform.name} (ID: ${platformId}) 的认证状态`);
            
            try {
                const response = await fetch(`/api/platforms/${platformId}/auth`);
                const authList = await response.json();
                
                console.log(`平台 ${platform.name} 的认证信息:`, authList);
                
                if (!authList || authList.length === 0) {
                    console.log(`平台 ${platform.name} 未配置认证信息`);
                    unauthenticatedPlatforms.push(platform);
                } else {
                    console.log(`平台 ${platform.name} 已配置认证信息`);
                }
            } catch (error) {
                console.error(`检查平台 ${platform.name} 认证状态失败:`, error);
                unauthenticatedPlatforms.push(platform);
            }
        }
        
        console.log('认证检查完成，未认证的平台:', unauthenticatedPlatforms.map(p => p.name));
        
        return {
            success: unauthenticatedPlatforms.length === 0,
            unauthenticatedPlatforms
        };
    }
    
    /**
     * 显示认证必须对话框
     */
    showAuthRequiredDialog(unauthenticatedPlatforms) {
        const platformNames = unauthenticatedPlatforms.map(p => p.name).join('、');
        
        const modalHtml = `
            <div class="modal fade" id="authRequiredModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-key text-warning me-2"></i>
                                需要平台认证
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                以下平台尚未配置认证信息，无法进行发布：
                            </div>
                            <ul class="list-group list-group-flush mb-3">
                                ${unauthenticatedPlatforms.map(platform => `
                                    <li class="list-group-item d-flex align-items-center">
                                        <i class="fas fa-globe text-primary me-2"></i>
                                        <strong>${platform.name}</strong>
                                        <span class="badge bg-danger ms-auto">未认证</span>
                                    </li>
                                `).join('')}
                            </ul>
                            <p class="mb-0">
                                <i class="fas fa-info-circle text-info me-2"></i>
                                请先在“平台管理”页面中配置相关平台的认证信息。
                            </p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="app.goToPlatformManagement()">
                                <i class="fas fa-cog me-2"></i>
                                去配置认证
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除旧的模态框（如果存在）
        const existingModal = document.getElementById('authRequiredModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加新的模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('authRequiredModal'));
        modal.show();
    }
    
    /**
     * 跳转到平台管理页面
     */
    goToPlatformManagement() {
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('authRequiredModal'));
        if (modal) {
            modal.hide();
        }
        
        // 切换到平台管理页面
        this.showSection('platforms');
    }
    
    /**
     * 显示认证配置对话框
     */
    async showAuthConfig(platformId, platformName) {
        const modalHtml = `
            <div class="modal fade" id="authConfigModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-key text-primary me-2"></i>
                                配置 ${platformName} 认证信息
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div id="auth-loading" class="text-center">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2">正在加载认证信息...</p>
                            </div>
                            <form id="auth-config-form" style="display: none;">
                                <div class="mb-3">
                                    <label class="form-label">用户标识 *</label>
                                    <input type="text" class="form-control" id="auth-user-identifier" 
                                           placeholder="输入用户名、邮箱或手机号" required>
                                    <div class="form-text">用于标识该平台的账户</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">访问令牌 (Access Token) *</label>
                                    <textarea class="form-control" id="auth-access-token" rows="3" 
                                              placeholder="输入从平台获取的API访问令牌" required></textarea>
                                    <div class="form-text">请在平台开发者中心获取API访问令牌</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">刷新令牌 (Refresh Token)</label>
                                    <textarea class="form-control" id="auth-refresh-token" rows="2" 
                                              placeholder="可选：输入刷新令牌（如果有）"></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Cookie 信息</label>
                                    <textarea class="form-control" id="auth-cookies" rows="2" 
                                              placeholder="可选：输入Cookie信息（适用于需要Cookie认证的平台）"></textarea>
                                    <div class="form-text">支持 Ctrl+V 粘贴</div>
                                </div>
                                
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>获取认证信息指引：</strong><br>
                                    <small>
                                        • <strong>头条号：</strong>访问 mp.toutiao.com → 账号管理 → API管理 获取<br>
                                        • <strong>微信公众号：</strong>访问 mp.weixin.qq.com → 设置与开发 → 基本配置 获取AppID和AppSecret<br>
                                        • <strong>B站：</strong>访问个人中心 → 创作中心 获取相关信息
                                    </small>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="app.saveAuthConfig(${platformId})">
                                <i class="fas fa-save me-2"></i>
                                保存认证信息
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除旧的模态框
        const existingModal = document.getElementById('authConfigModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加新的模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('authConfigModal'), {
            keyboard: true,  // 允许键盘事件
            backdrop: true
        });
        modal.show();
        
        // 等待模态框完全显示后，加载现有认证信息
        const modalElement = document.getElementById('authConfigModal');
        modalElement.addEventListener('shown.bs.modal', async () => {
            try {
                // 加载现有认证信息
                await this.loadExistingAuthConfig(platformId);
                
                // 隐藏加载状态，显示表单
                document.getElementById('auth-loading').style.display = 'none';
                document.getElementById('auth-config-form').style.display = 'block';
                
                // 确保所有输入框能正常响应键盘事件
                const textareas = modalElement.querySelectorAll('textarea, input[type="text"]');
                textareas.forEach(textarea => {
                    // 允许所有键盘事件
                    textarea.addEventListener('keydown', (e) => {
                        // 阻止事件被模态框拦截
                        e.stopPropagation();
                    });
                    
                    // 特别处理粘贴事件
                    textarea.addEventListener('paste', (e) => {
                        e.stopPropagation();
                        console.log('粘贴事件触发:', e.target.id);
                    });
                    
                    // 右键菜单事件
                    textarea.addEventListener('contextmenu', (e) => {
                        e.stopPropagation();
                    });
                });
                
                console.log('认证配置对话框已显示，认证信息已加载，键盘事件已启用');
            } catch (error) {
                console.error('加载认证信息失败:', error);
                // 出错时也要显示表单
                document.getElementById('auth-loading').style.display = 'none';
                document.getElementById('auth-config-form').style.display = 'block';
                this.showAlert('加载现有认证信息失败，请重新填写', 'warning');
            }
        });
    }

    /**
     * 加载现有的认证配置信息
     */
    async loadExistingAuthConfig(platformId) {
        try {
            console.log(`开始加载平台 ${platformId} 的现有认证信息`);
            
            const response = await fetch(`/api/platforms/${platformId}/auth`);
            if (!response.ok) {
                throw new Error('获取认证信息失败');
            }
            
            const authList = await response.json();
            console.log(`平台 ${platformId} 的认证信息:`, authList);
            
            // 如果有认证信息，加载第一个（通常平台只有一个认证信息）
            if (authList && authList.length > 0) {
                const auth = authList[0];
                
                // 填充表单字段
                const userIdentifierField = document.getElementById('auth-user-identifier');
                const accessTokenField = document.getElementById('auth-access-token');
                const refreshTokenField = document.getElementById('auth-refresh-token');
                const cookiesField = document.getElementById('auth-cookies');
                
                if (userIdentifierField && auth.userIdentifier) {
                    userIdentifierField.value = auth.userIdentifier;
                }
                
                if (accessTokenField && auth.accessToken) {
                    accessTokenField.value = auth.accessToken;
                }
                
                if (refreshTokenField && auth.refreshToken) {
                    refreshTokenField.value = auth.refreshToken;
                }
                
                if (cookiesField && auth.cookies) {
                    cookiesField.value = auth.cookies;
                }
                
                console.log(`平台 ${platformId} 的认证信息已加载到表单`);
            } else {
                console.log(`平台 ${platformId} 暂无认证信息`);
            }
            
        } catch (error) {
            console.error('加载现有认证信息失败:', error);
            // 即使加载失败也不要抛出异常，让用户可以手动填写
        }
    }
    
    /**
     * 保存认证配置
     */
    async saveAuthConfig(platformId) {
        const userIdentifier = document.getElementById('auth-user-identifier').value.trim();
        const accessToken = document.getElementById('auth-access-token').value.trim();
        const refreshToken = document.getElementById('auth-refresh-token').value.trim();
        const cookies = document.getElementById('auth-cookies').value.trim();
        
        if (!userIdentifier || !accessToken) {
            this.showAlert('请填写必需的认证信息', 'warning');
            return;
        }
        
        try {
            const response = await fetch(`/api/platforms/${platformId}/auth`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userIdentifier,
                    accessToken,
                    refreshToken: refreshToken || null,
                    cookies: cookies || null
                })
            });
            
            if (!response.ok) {
                throw new Error('保存认证信息失败');
            }
            
            this.showAlert('认证信息保存成功！', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('authConfigModal'));
            if (modal) {
                modal.hide();
            }
            
            // 智能更新UI：根据当前页面状态决定如何更新
            await this.updateUIAfterAuthSave(platformId);
            
        } catch (error) {
            console.error('保存认证信息失败:', error);
            this.showAlert('保存认证信息失败: ' + error.message, 'danger');
        }
    }

    /**
     * 更新UI后智能更新
     */
    async updateUIAfterAuthSave(platformId) {
        try {
            // 检查当前页面是否是平台管理页面
            const platformsSection = document.getElementById('platforms-section');
            const isPlatformManagementPage = platformsSection && platformsSection.classList.contains('active');
            
            if (isPlatformManagementPage) {
                // 如果在平台管理页面，重新加载平台配置
                console.log('当前在平台管理页面，重新加载平台配置');
                await this.loadPlatformConfig();
            } else {
                // 如果在其他页面（如内容上传页面），更新平台列表
                console.log('当前不在平台管理页面，更新平台列表');
                await this.renderPlatforms();
            }
            
            console.log(`平台 ${platformId} 认证保存后 UI 更新完成`);
            
        } catch (error) {
            console.error('更新UI失败:', error);
            // UI更新失败不影响主流程，只记录日志
        }
    }
    
    /**
     * 判断是否为Markdown文件
     */
    isMarkdownFile(filename) {
        const extension = filename.split('.').pop().toLowerCase();
        return extension === 'md' || extension === 'markdown';
    }
    
    /**
     * 设置文档预览和编辑功能
     */
    setupDocumentPreviewAndEdit() {
        const previewBtn = document.getElementById('preview-btn');
        const editBtn = document.getElementById('edit-btn');
        const closePreviewBtn = document.getElementById('close-preview-btn');
        
        if (previewBtn) {
            previewBtn.addEventListener('click', () => {
                this.previewDocument();
            });
        }
        
        if (editBtn) {
            editBtn.addEventListener('click', () => {
                this.editDocument();
            });
        }
        
        if (closePreviewBtn) {
            closePreviewBtn.addEventListener('click', () => {
                this.closeDocumentPreview();
            });
        }
    }
    
    /**
     * 预览文档
     */
    async previewDocument() {
        if (!this.currentFile || !this.isMarkdownFile(this.currentFile.name)) {
            this.showAlert('请选择一个Markdown文件', 'warning');
            return;
        }
        
        try {
            console.log('开始预览文档:', this.currentFile.name);
            
            // 读取文件内容
            const content = await this.readFileContent(this.currentFile);
            
            // 将Markdown转换为HTML
            const htmlContent = await this.convertMarkdownToHtml(content);
            
            // 显示预览区域
            const previewArea = document.getElementById('document-preview-area');
            const previewContent = document.getElementById('document-preview-content');
            
            previewContent.innerHTML = htmlContent;
            previewArea.classList.remove('d-none');
            
            console.log('文档预览显示成功');
            
        } catch (error) {
            console.error('预览文档失败:', error);
            this.showAlert('预览文档失败: ' + error.message, 'danger');
        }
    }
    
    /**
     * 关闭文档预览
     */
    closeDocumentPreview() {
        const previewArea = document.getElementById('document-preview-area');
        previewArea.classList.add('d-none');
    }
    
    /**
     * 编辑文档
     */
    async editDocument() {
        if (!this.currentFile || !this.isMarkdownFile(this.currentFile.name)) {
            this.showAlert('请选择一个Markdown文件', 'warning');
            return;
        }
        
        try {
            console.log('开始编辑文档:', this.currentFile.name);
            
            // 读取文件内容
            const content = await this.readFileContent(this.currentFile);
            
            // 在编辑器中显示内容
            const editorTextarea = document.getElementById('documentEditor');
            editorTextarea.value = content;
            
            // 更新模态框标题
            const modalTitle = document.getElementById('documentEditorModalLabel');
            modalTitle.innerHTML = `
                <i class="fas fa-edit me-2"></i>
                编辑: ${this.currentFile.name}
            `;
            
            // 显示编辑器模态框
            const editorModal = new bootstrap.Modal(document.getElementById('documentEditorModal'));
            editorModal.show();
            
            // 初始更新预览
            this.updateLivePreview();
            
            console.log('编辑器显示成功');
            
        } catch (error) {
            console.error('打开编辑器失败:', error);
            this.showAlert('打开编辑器失败: ' + error.message, 'danger');
        }
    }
    
    /**
     * 读取文件内容
     */
    readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (e) => reject(new Error('文件读取失败'));
            reader.readAsText(file, 'UTF-8');
        });
    }
    
    /**
     * 将Markdown转换为HTML
     */
    async convertMarkdownToHtml(markdownContent) {
        try {
            // 发送到服务器转换
            const response = await fetch('/api/markdown/convert', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content: markdownContent })
            });
            
            if (!response.ok) {
                throw new Error('服务器转换失败');
            }
            
            const result = await response.json();
            return result.html || markdownContent;
            
        } catch (error) {
            console.warn('Markdown转换失败，使用原始内容:', error);
            // 如果服务器转换失败，使用简单的客户端转换
            return this.simpleMarkdownToHtml(markdownContent);
        }
    }
    
    /**
     * 简单的Markdown转换（客户端）
     */
    simpleMarkdownToHtml(markdown) {
        return markdown
            .replace(/^### (.*$)/gim, '<h3>$1</h3>')
            .replace(/^## (.*$)/gim, '<h2>$1</h2>')
            .replace(/^# (.*$)/gim, '<h1>$1</h1>')
            .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/gim, '<em>$1</em>')
            .replace(/!\[([^\]]*)\]\(([^\)]*)\)/gim, '<img alt="$1" src="$2" class="img-fluid">')
            .replace(/\[([^\]]*)\]\(([^\)]*)\)/gim, '<a href="$2">$1</a>')
            .replace(/\n/gim, '<br>');
    }
    
    /**
     * 设置在线编辑器
     */
    setupDocumentEditor() {
        // 编辑器工具栏事件
        this.setupEditorToolbar();
        
        // 实时预览功能
        this.setupLivePreview();
        
        // 图片上传功能
        this.setupImageUploadInEditor();
        
        // 保存按钮
        this.setupEditorSave();
    }
    
    /**
     * 设置编辑器工具栏
     */
    setupEditorToolbar() {
        const toolbar = document.querySelector('.editor-toolbar');
        if (!toolbar) return;
        
        toolbar.addEventListener('click', (e) => {
            const button = e.target.closest('button[data-action]');
            if (!button) return;
            
            const action = button.dataset.action;
            this.handleToolbarAction(action);
        });
    }
    
    /**
     * 处理工具栏操作
     */
    handleToolbarAction(action) {
        const editor = document.getElementById('documentEditor');
        if (!editor) return;
        
        const start = editor.selectionStart;
        const end = editor.selectionEnd;
        const selectedText = editor.value.substring(start, end);
        
        let replacement = '';
        let cursorOffset = 0;
        
        switch (action) {
            case 'bold':
                replacement = `**${selectedText}**`;
                cursorOffset = selectedText ? 0 : 2;
                break;
            case 'italic':
                replacement = `*${selectedText}*`;
                cursorOffset = selectedText ? 0 : 1;
                break;
            case 'h1':
                replacement = `# ${selectedText}`;
                cursorOffset = selectedText ? 0 : 2;
                break;
            case 'h2':
                replacement = `## ${selectedText}`;
                cursorOffset = selectedText ? 0 : 3;
                break;
            case 'h3':
                replacement = `### ${selectedText}`;
                cursorOffset = selectedText ? 0 : 4;
                break;
            case 'ul':
                replacement = `- ${selectedText}`;
                cursorOffset = selectedText ? 0 : 2;
                break;
            case 'ol':
                replacement = `1. ${selectedText}`;
                cursorOffset = selectedText ? 0 : 3;
                break;
            case 'quote':
                replacement = `> ${selectedText}`;
                cursorOffset = selectedText ? 0 : 2;
                break;
            case 'code':
                if (selectedText.includes('\n')) {
                    replacement = `\`\`\`\n${selectedText}\n\`\`\``;
                    cursorOffset = selectedText ? 0 : 4;
                } else {
                    replacement = `\`${selectedText}\``;
                    cursorOffset = selectedText ? 0 : 1;
                }
                break;
            case 'link':
                replacement = `[${selectedText || '链接文本'}](链接地址)`;
                cursorOffset = selectedText ? replacement.length - 1 - 4 : 1;
                break;
            case 'table':
                replacement = `\n| 表头1 | 表头2 | 表头3 |\n|-------|-------|-------|\n| 单元格1 | 单元格2 | 单元格3 |\n`;
                cursorOffset = 0;
                break;
            case 'image':
                // 显示图片上传模态框
                const imageModal = new bootstrap.Modal(document.getElementById('imageUploadModal'));
                imageModal.show();
                return;
        }
        
        // 替换选中文本
        editor.value = editor.value.substring(0, start) + replacement + editor.value.substring(end);
        
        // 设置光标位置
        const newCursorPos = start + replacement.length - cursorOffset;
        editor.setSelectionRange(newCursorPos, newCursorPos);
        
        // 聚焦到编辑器
        editor.focus();
        
        // 更新预览
        this.updateLivePreview();
    }
    
    /**
     * 设置实时预览
     */
    setupLivePreview() {
        const editor = document.getElementById('documentEditor');
        const previewToggle = document.getElementById('realTimePreview');
        
        if (editor) {
            editor.addEventListener('input', () => {
                if (previewToggle && previewToggle.checked) {
                    this.updateLivePreview();
                }
            });
        }
        
        if (previewToggle) {
            previewToggle.addEventListener('change', () => {
                const previewPane = document.getElementById('documentPreviewPane');
                if (previewToggle.checked) {
                    previewPane.style.display = 'block';
                    this.updateLivePreview();
                } else {
                    previewPane.style.display = 'none';
                }
            });
        }
    }
    
    /**
     * 更新实时预览
     */
    async updateLivePreview() {
        const editor = document.getElementById('documentEditor');
        const preview = document.getElementById('documentLivePreview');
        
        if (!editor || !preview) return;
        
        const content = editor.value;
        if (!content.trim()) {
            preview.innerHTML = '<p class="text-muted text-center mt-5">在左侧编辑器中输入内容，预览将在这里显示...</p>';
            return;
        }
        
        try {
            const html = await this.convertMarkdownToHtml(content);
            preview.innerHTML = html;
        } catch (error) {
            console.error('更新预览失败:', error);
        }
    }
    
    /**
     * 设置编辑器中的图片上传
     */
    setupImageUploadInEditor() {
        const uploadArea = document.getElementById('editorImageUploadArea');
        const fileInput = document.getElementById('editorImageInput');
        const insertFromUrlBtn = document.getElementById('insertImageFromUrl');
        const confirmUploadBtn = document.getElementById('confirmImageUpload');
        const cancelUploadBtn = document.getElementById('cancelImageUpload');
        
        // 点击上传区域
        if (uploadArea) {
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });
        }
        
        // 文件选择
        if (fileInput) {
            fileInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    this.previewEditorImage(file);
                }
            });
        }
        
        // 从 URL 插入图片
        if (insertFromUrlBtn) {
            insertFromUrlBtn.addEventListener('click', () => {
                this.insertImageFromUrl();
            });
        }
        
        // 确认上传
        if (confirmUploadBtn) {
            confirmUploadBtn.addEventListener('click', () => {
                this.confirmImageUpload();
            });
        }
        
        // 取消上传
        if (cancelUploadBtn) {
            cancelUploadBtn.addEventListener('click', () => {
                this.cancelImageUpload();
            });
        }
    }
    
    /**
     * 预览编辑器图片
     */
    previewEditorImage(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const previewContainer = document.getElementById('uploadImagePreview');
            const previewImg = document.getElementById('previewImg');
            
            previewImg.src = e.target.result;
            previewContainer.classList.remove('d-none');
            
            // 隐藏上传区域
            document.getElementById('editorImageUploadArea').style.display = 'none';
        };
        reader.readAsDataURL(file);
    }
    
    /**
     * 确认上传图片
     */
    async confirmImageUpload() {
        const fileInput = document.getElementById('editorImageInput');
        const file = fileInput.files[0];
        
        if (!file) {
            this.showAlert('请选择图片文件', 'warning');
            return;
        }
        
        try {
            console.log('开始上传编辑器图片:', file.name);
            
            // 上传图片
            const uploadResult = await this.uploadImage(file, 'documents');
            
            if (uploadResult.success) {
                // 插入图片到编辑器
                const imageMarkdown = `![${file.name}](${uploadResult.url})`;
                this.insertTextToEditor(imageMarkdown);
                
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('imageUploadModal'));
                if (modal) {
                    modal.hide();
                }
                
                // 重置上传状态
                this.resetImageUploadModal();
                
                console.log('图片上传并插入成功');
                
            } else {
                this.showAlert('图片上传失败: ' + uploadResult.error, 'danger');
            }
            
        } catch (error) {
            console.error('图片上传失败:', error);
            this.showAlert('图片上传失败: ' + error.message, 'danger');
        }
    }
    
    /**
     * 取消图片上传
     */
    cancelImageUpload() {
        this.resetImageUploadModal();
    }
    
    /**
     * 重置图片上传模态框
     */
    resetImageUploadModal() {
        const fileInput = document.getElementById('editorImageInput');
        const previewContainer = document.getElementById('uploadImagePreview');
        const uploadArea = document.getElementById('editorImageUploadArea');
        
        fileInput.value = '';
        previewContainer.classList.add('d-none');
        uploadArea.style.display = 'block';
    }
    
    /**
     * 从 URL 插入图片
     */
    insertImageFromUrl() {
        const urlInput = document.getElementById('imageUrlInput');
        const altInput = document.getElementById('imageAltInput');
        const titleInput = document.getElementById('imageTitleInput');
        
        const url = urlInput.value.trim();
        const alt = altInput.value.trim() || '图片';
        const title = titleInput.value.trim();
        
        if (!url) {
            this.showAlert('请输入图片URL', 'warning');
            return;
        }
        
        // 生成 Markdown 图片语法
        let imageMarkdown = `![${alt}](${url}`;
        if (title) {
            imageMarkdown += ` "${title}"`;
        }
        imageMarkdown += ')';
        
        // 插入到编辑器
        this.insertTextToEditor(imageMarkdown);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('imageUploadModal'));
        if (modal) {
            modal.hide();
        }
        
        // 清空表单
        urlInput.value = '';
        altInput.value = '';
        titleInput.value = '';
        
        console.log('网络图片插入成功:', imageMarkdown);
    }
    
    /**
     * 向编辑器插入文本
     */
    insertTextToEditor(text) {
        const editor = document.getElementById('documentEditor');
        if (!editor) return;
        
        const cursorPos = editor.selectionStart;
        const textBefore = editor.value.substring(0, cursorPos);
        const textAfter = editor.value.substring(editor.selectionEnd);
        
        editor.value = textBefore + text + textAfter;
        
        // 设置光标位置
        const newCursorPos = cursorPos + text.length;
        editor.setSelectionRange(newCursorPos, newCursorPos);
        
        // 聚焦到编辑器
        editor.focus();
        
        // 更新预览
        this.updateLivePreview();
    }
    
    /**
     * 设置编辑器保存
     */
    setupEditorSave() {
        const saveBtn = document.getElementById('saveDocumentBtn');
        
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.saveDocument();
            });
        }
        
        // 快捷键保存 (Ctrl+S)
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                const modal = document.getElementById('documentEditorModal');
                if (modal && modal.classList.contains('show')) {
                    e.preventDefault();
                    this.saveDocument();
                }
            }
        });
    }
    
    /**
     * 保存文档
     */
    async saveDocument() {
        const editor = document.getElementById('documentEditor');
        if (!editor || !this.currentFile) {
            this.showAlert('没有可保存的文档', 'warning');
            return;
        }
        
        try {
            console.log('开始保存文档');
            
            const content = editor.value;
            
            // 创建新的文件对象
            const blob = new Blob([content], { type: 'text/markdown' });
            const file = new File([blob], this.currentFile.name, { type: 'text/markdown' });
            
            // 更新当前文件
            this.currentFile = file;
            
            this.showAlert('文档保存成功！', 'success');
            
            console.log('文档保存成功');
            
        } catch (error) {
            console.error('保存文档失败:', error);
            this.showAlert('保存文档失败: ' + error.message, 'danger');
        }
    }
    
    /**
     * 测试平台连接
     */
    async testPlatformAuth(platformId, platformName) {
        try {
            this.showAlert(`正在测试 ${platformName} 连接...`, 'info');
            
            // 这里可以实现具体的连接测试逻辑
            // 例如调用一个测试接口
            
            setTimeout(() => {
                this.showAlert(`${platformName} 连接测试成功！`, 'success');
            }, 1500);
            
        } catch (error) {
            console.error('测试平台连接失败:', error);
            this.showAlert(`${platformName} 连接测试失败: ` + error.message, 'danger');
        }
    }
    
    // 显示发布进度
    showPublishProgress() {
        const progressDiv = document.getElementById('publish-status');
        const progressContainer = document.getElementById('publish-progress');
        
        progressContainer.innerHTML = `
            <div class="d-flex align-items-center">
                <div class="spinner-border spinner-border-sm me-2" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <span>正在发布到平台...</span>
            </div>
        `;
        
        progressDiv.style.display = 'block';
    }
    
    // 隐藏发布进度
    hidePublishProgress() {
        const progressDiv = document.getElementById('publish-status');
        progressDiv.style.display = 'none';
    }
    
    // 更新发布按钮状态
    updatePublishButton(isPublishing) {
        const publishBtn = document.getElementById('publish-btn');
        if (publishBtn) {
            publishBtn.disabled = isPublishing;
            if (isPublishing) {
                publishBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>发布中...';
            } else {
                publishBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>开始发布';
            }
        }
    }
    
    // 重置表单
    resetForm() {
        this.currentFile = null;
        this.selectedPlatforms.clear();
        
        document.getElementById('file-input').value = '';
        document.getElementById('file-info').classList.add('d-none');
        document.getElementById('content-form').reset();
        
        // 取消所有平台选择
        document.querySelectorAll('.platform-card input[type="checkbox"]').forEach(checkbox => {
            checkbox.checked = false;
        });
        
        document.querySelectorAll('.platform-card').forEach(card => {
            card.classList.remove('selected');
        });
    }
    
    // 加载文章列表
    async loadArticles(page = 0) {
        try {
            const response = await fetch(`/api/articles?page=${page}&size=10`);
            const data = await response.json();
            this.renderArticlesList(data.content);
            this.renderPagination('articles', data);
        } catch (error) {
            console.error('加载文章列表失败:', error);
            this.showAlert('加载文章列表失败', 'danger');
        }
    }
    
    // 渲染文章列表
    renderArticlesList(articles) {
        const tbody = document.getElementById('articles-table-body');
        
        tbody.innerHTML = articles.map(article => `
            <tr>
                <td>
                    <div>
                        <strong>${article.title}</strong>
                        <br>
                        <small class="text-muted">${article.summary || '无摘要'}</small>
                    </div>
                </td>
                <td>
                    <span class="badge status-badge ${this.getStatusBadgeClass(article.status)}">
                        ${this.getStatusText(article.status)}
                    </span>
                </td>
                <td>
                    <small>${this.formatDateTime(article.createdAt)}</small>
                </td>
                <td>
                    <small>${article.publishConfigs ? article.publishConfigs.length : 0} 个平台</small>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="app.editArticle(${article.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-success" onclick="app.republishArticle(${article.id})">
                            <i class="fas fa-redo"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="app.deleteArticle(${article.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }
    
    // 加载视频列表
    async loadVideos(page = 0) {
        try {
            const response = await fetch(`/api/videos?page=${page}&size=10`);
            const data = await response.json();
            this.renderVideosList(data.content);
            this.renderPagination('videos', data);
        } catch (error) {
            console.error('加载视频列表失败:', error);
            this.showAlert('加载视频列表失败', 'danger');
        }
    }
    
    // 渲染视频列表
    renderVideosList(videos) {
        const tbody = document.getElementById('videos-table-body');
        
        tbody.innerHTML = videos.map(video => `
            <tr>
                <td>
                    <div>
                        <strong>${video.title}</strong>
                        <br>
                        <small class="text-muted">${video.description || '无描述'}</small>
                    </div>
                </td>
                <td>
                    <small>${video.duration ? Math.floor(video.duration / 60) + ':' + (video.duration % 60).toString().padStart(2, '0') : '未知'}</small>
                </td>
                <td>
                    <span class="badge status-badge ${this.getStatusBadgeClass(video.status)}">
                        ${this.getStatusText(video.status)}
                    </span>
                </td>
                <td>
                    <small>${this.formatDateTime(video.createdAt)}</small>
                </td>
                <td>
                    <small>${video.publishConfigs ? video.publishConfigs.length : 0} 个平台</small>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="app.editVideo(${video.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-success" onclick="app.republishVideo(${video.id})">
                            <i class="fas fa-redo"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="app.deleteVideo(${video.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }
    
    // 获取状态徽章样式
    getStatusBadgeClass(status) {
        const classes = {
            'DRAFT': 'bg-secondary',
            'PUBLISHING': 'bg-warning',
            'PUBLISHED': 'bg-success',
            'FAILED': 'bg-danger',
            'SCHEDULED': 'bg-info'
        };
        return classes[status] || 'bg-secondary';
    }
    
    // 获取状态文本
    getStatusText(status) {
        const texts = {
            'DRAFT': '草稿',
            'PUBLISHING': '发布中',
            'PUBLISHED': '已发布',
            'FAILED': '失败',
            'SCHEDULED': '定时发布'
        };
        return texts[status] || status;
    }
    
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN');
    }
    
    // 渲染分页
    renderPagination(type, data) {
        const paginationContainer = document.getElementById(`${type}-pagination`);
        
        if (data.totalPages <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }
        
        let paginationHtml = '';
        
        // 上一页
        if (data.number > 0) {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="app.load${type.charAt(0).toUpperCase() + type.slice(1)}(${data.number - 1})">上一页</a>
                </li>
            `;
        }
        
        // 页码
        for (let i = Math.max(0, data.number - 2); i <= Math.min(data.totalPages - 1, data.number + 2); i++) {
            paginationHtml += `
                <li class="page-item ${i === data.number ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="app.load${type.charAt(0).toUpperCase() + type.slice(1)}(${i})">${i + 1}</a>
                </li>
            `;
        }
        
        // 下一页
        if (data.number < data.totalPages - 1) {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="app.load${type.charAt(0).toUpperCase() + type.slice(1)}(${data.number + 1})">下一页</a>
                </li>
            `;
        }
        
        paginationContainer.innerHTML = paginationHtml;
    }
    
    // 加载平台配置
    async loadPlatformConfig() {
        const configContainer = document.getElementById('platforms-config');
        
        // 为每个平台获取认证状态
        const platformsWithAuth = await Promise.all(
            this.platforms.map(async (platform) => {
                try {
                    const response = await fetch(`/api/platforms/${platform.id}/auth`);
                    const authList = await response.json();
                    return {
                        ...platform,
                        hasAuth: authList && authList.length > 0,
                        authCount: authList ? authList.length : 0
                    };
                } catch (error) {
                    return {
                        ...platform,
                        hasAuth: false,
                        authCount: 0
                    };
                }
            })
        );
        
        configContainer.innerHTML = `
            <div class="row">
                ${platformsWithAuth.map(platform => `
                    <div class="col-md-6 mb-3">
                        <div class="card h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h6 class="card-title mb-0">
                                        <i class="fas fa-globe text-primary me-2"></i>
                                        ${platform.name}
                                    </h6>
                                    <span class="badge ${platform.enabled ? 'bg-success' : 'bg-secondary'}">
                                        ${platform.enabled ? '已启用' : '已禁用'}
                                    </span>
                                </div>
                                <p class="text-muted small mb-3">${platform.description || '暂无描述'}</p>
                                
                                ${platform.code === 'toutiao' ? `
                                    <div class="alert alert-info py-2 mb-3">
                                        <i class="fas fa-info-circle me-1"></i>
                                        <small>头条平台支持使用网页登录Cookies，无需API密钥。</small>
                                    </div>
                                ` : ''}
                                
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <div>
                                        <small class="text-muted">认证状态：</small>
                                        <span class="badge ${platform.hasAuth ? 'bg-success' : 'bg-danger'} ms-1">
                                            ${platform.hasAuth ? '已认证' : '未认证'}
                                        </span>
                                    </div>
                                    <div>
                                        <small class="text-muted">支持类型：</small>
                                        <span class="badge bg-info ms-1">${platform.supportedTypes}</span>
                                    </div>
                                </div>
                                
                                <div class="d-flex gap-2">
                                    <button class="btn btn-sm ${platform.hasAuth ? 'btn-outline-primary' : 'btn-primary'}" 
                                            onclick="app.showAuthConfig(${platform.id}, '${platform.name}')">
                                        <i class="fas ${platform.hasAuth ? 'fa-edit' : 'fa-plus'} me-1"></i>
                                        ${platform.hasAuth ? '管理认证' : '配置认证'}
                                    </button>
                                    ${platform.hasAuth ? `
                                        <button class="btn btn-sm btn-outline-success" 
                                                onclick="app.testPlatformAuth(${platform.id}, '${platform.name}')">
                                            <i class="fas fa-check me-1"></i>
                                            测试连接
                                        </button>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    }
    
    // 显示认证配置
    showAuthConfig(platformId, platformName) {
        // 设置平台选择器
        const authPlatformSelect = document.getElementById('auth-platform');
        if (authPlatformSelect) {
            authPlatformSelect.value = platformId;
            
            // 触发平台变化事件
            const platform = this.platforms.find(p => p.id == platformId);
            const platformCode = platform ? platform.code : '';
            this.handlePlatformAuthChange(platformCode, platformId);
        }
        
        // 切换到平台管理页面（如果当前不在该页面）
        this.showSection('platforms');
        
        // 滚动到认证信息区域
        setTimeout(() => {
            const authCard = document.querySelector('#platforms-section .col-lg-4 .card');
            if (authCard) {
                authCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }, 100);
    }
    
    // 测试平台认证
    async testPlatformAuth(platformId, platformName) {
        const btn = event.target;
        const originalContent = btn.innerHTML;
        
        try {
            // 更新按钮状态
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>测试中...';
            btn.disabled = true;
            
            // 1. 获取认证信息
            const response = await fetch(`/api/platforms/${platformId}/auth`);
            if (!response.ok) {
                throw new Error('获取认证信息失败');
            }
            
            const authList = await response.json();
            console.log('authList', authList);
            if (!authList || authList.length === 0) {
                throw new Error('未找到认证信息，请先配置认证');
            }
            
            const auth = authList[0];
            const platform = this.platforms.find(p => p.id == platformId);
            
            // 2. 执行测试
            let testResult;
            if (platform.code === 'toutiao') {
                console.log('toutiao auth', auth);
                testResult = await this.testToutiaoAuth(auth, platform);
            } else {
                testResult = await this.testGeneralAuth(auth, platform);
            }
            
            // 3. 显示测试结果
            if (testResult.success) {
                this.showAlert(`${platformName} 认证测试成功！`, 'success');
                
                // 如果返回了用户信息，显示详细信息
                if (testResult.userInfo) {
                    const userInfo = testResult.userInfo;
                    const infoText = userInfo.name ? `用户：${userInfo.name}` : 
                                   userInfo.screen_name ? `用户：${userInfo.screen_name}` :
                                   userInfo.id ? `用户ID：${userInfo.id}` : '认证有效';
                    
                    setTimeout(() => {
                        this.showAlert(`认证详情 - ${infoText}`, 'info');
                    }, 1000);
                }
                
                // 如果有管理页面URL，询问是否打开
                if (testResult.managementUrl) {
                    setTimeout(() => {
                        if (confirm(`测试成功！是否打开${platformName}管理页面？`)) {
                            window.open(testResult.managementUrl, '_blank');
                        }
                    }, 2000);
                }
            } else {
                this.showAlert(`${platformName} 认证测试失败：${testResult.message}`, 'danger');
                
                // 如果是认证失效，建议重新配置
                if (testResult.needReconfig) {
                    setTimeout(() => {
                        if (confirm('认证信息可能已失效，是否重新配置？')) {
                            this.showAuthConfig(platformId, platformName);
                        }
                    }, 1000);
                }
            }
            
        } catch (error) {
            console.error('测试认证失败:', error);
            this.showAlert(`测试失败：${error.message}`, 'danger');
        } finally {
            // 恢复按钮状态
            btn.innerHTML = originalContent;
            btn.disabled = false;
        }
    }
    
    // 测试头条号认证
    async testToutiaoAuth(auth, platform) {
        try {
            // 使用后端验证API
            const response = await fetch('/api/platforms/toutiao/validate-cookies', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ cookies: auth.cookies })
            });
            
            const result = await response.json();
            
            if (result.success && result.valid) {
                return {
                    success: true,
                    userInfo: result.userInfo,
                    managementUrl: 'https://mp.toutiao.com/profile_v3/graphic/publish'
                };
            } else {
                return {
                    success: false,
                    message: result.message || 'Cookies验证失败',
                    needReconfig: true
                };
            }
        } catch (error) {
            return {
                success: false,
                message: error.message,
                needReconfig: true
            };
        }
    }
    
    // 测试通用平台认证
    async testGeneralAuth(auth, platform) {
        try {
            // 调用后端验证API
            const response = await fetch(`/api/platforms/${platform.id}/test-auth`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    accessToken: auth.accessToken,
                    cookies: auth.cookies
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                return {
                    success: true,
                    userInfo: result.userInfo,
                    managementUrl: platform.websiteUrl
                };
            } else {
                return {
                    success: false,
                    message: result.message || '认证验证失败',
                    needReconfig: result.needReconfig || false
                };
            }
        } catch (error) {
            return {
                success: false,
                message: error.message,
                needReconfig: true
            };
        }
    }
    
    // 设置表单提交
    setupForms() {
        // 认证表单
        document.getElementById('auth-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.saveAuthInfo();
        });
        
        // 平台选择变化事件
        const authPlatformSelect = document.getElementById('auth-platform');
        if (authPlatformSelect) {
            authPlatformSelect.addEventListener('change', (e) => {
                const platformId = e.target.value;
                // 通过ID查找平台代码
                const platform = this.platforms.find(p => p.id == platformId);
                const platformCode = platform ? platform.code : '';
                this.handlePlatformAuthChange(platformCode, platformId);
            });
        }
        
        // 头条cookies相关按钮
        this.setupToutiaoCookiesHandlers();
        
        // 设置表单
        document.getElementById('settings-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            this.showAlert('设置已保存', 'success');
        });
    }
    
    // 保存认证信息
    async saveAuthInfo() {
        const platformId = document.getElementById('auth-platform').value;
        const userIdentifier = document.getElementById('auth-user').value;
        
        if (!platformId || !userIdentifier) {
            this.showAlert('请填写平台和用户标识', 'warning');
            return;
        }
        
        let authData = {
            userIdentifier
        };
        
        // 根据平台类型准备认证数据
        const platform = this.platforms.find(p => p.id == platformId);
        if (platform && platform.code === 'toutiao') {
            // 头条平台优先使用cookies
            const toutiaoCookies = document.getElementById('auth-cookies-toutiao').value.trim();
            if (toutiaoCookies) {
                authData.cookies = toutiaoCookies;
            } else {
                this.showAlert('请输入或获取头条号Cookies', 'warning');
                return;
            }
        } else {
            // 传统平台使用token
            const accessToken = document.getElementById('auth-token').value.trim();
            const cookies = document.getElementById('auth-cookies').value.trim();
            
            if (!accessToken) {
                this.showAlert('请填写访问令牌', 'warning');
                return;
            }
            
            authData.accessToken = accessToken;
            if (cookies) {
                authData.cookies = cookies;
            }
        }
        
        try {
            const response = await fetch(`/api/platforms/${platformId}/auth`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(authData)
            });
            
            if (!response.ok) {
                throw new Error('保存认证信息失败');
            }
            
            this.showAlert('认证信息保存成功', 'success');
            
            // 清空表单
            document.getElementById('auth-form').reset();
            document.getElementById('auth-platform').value = '';
            this.handlePlatformAuthChange('', '');
            
            // 重新加载平台列表以显示更新后的认证状态
            await this.loadPlatforms();
            
        } catch (error) {
            console.error('保存认证信息失败:', error);
            this.showAlert('保存认证信息失败: ' + error.message, 'danger');
        }
    }
    
    // 设置搜索功能
    setupSearch() {
        // 文章搜索
        document.getElementById('search-articles-btn').addEventListener('click', () => {
            this.searchArticles();
        });
        
        document.getElementById('article-search').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchArticles();
            }
        });
        
        // 视频搜索
        document.getElementById('search-videos-btn').addEventListener('click', () => {
            this.searchVideos();
        });
        
        document.getElementById('video-search').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchVideos();
            }
        });
    }
    
    // 搜索文章
    async searchArticles() {
        const keyword = document.getElementById('article-search').value.trim();
        if (!keyword) {
            this.loadArticles();
            return;
        }
        
        try {
            const response = await fetch(`/api/articles/search?title=${encodeURIComponent(keyword)}`);
            const articles = await response.json();
            this.renderArticlesList(articles);
            
            // 清空分页
            document.getElementById('articles-pagination').innerHTML = '';
            
        } catch (error) {
            console.error('搜索文章失败:', error);
            this.showAlert('搜索文章失败', 'danger');
        }
    }
    
    // 搜索视频
    async searchVideos() {
        const keyword = document.getElementById('video-search').value.trim();
        if (!keyword) {
            this.loadVideos();
            return;
        }
        
        try {
            const response = await fetch(`/api/videos/search?title=${encodeURIComponent(keyword)}`);
            const videos = await response.json();
            this.renderVideosList(videos);
            
            // 清空分页
            document.getElementById('videos-pagination').innerHTML = '';
            
        } catch (error) {
            console.error('搜索视频失败:', error);
            this.showAlert('搜索视频失败', 'danger');
        }
    }
    
    // 显示提示信息
    showAlert(message, type = 'info') {
        // 创建提示框
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 3000);
    }
    
    // 文章操作方法
    async editArticle(id) {
        try {
            // 获取文章详情
            const response = await fetch(`/api/articles/${id}`);
            if (!response.ok) {
                throw new Error('获取文章详情失败');
            }
            
            const article = await response.json();
            this.showEditArticleModal(article);
            
        } catch (error) {
            console.error('获取文章详情失败:', error);
            this.showAlert('获取文章详情失败: ' + error.message, 'danger');
        }
    }
    
    // 显示文章编辑模态框
    showEditArticleModal(article) {
        const modalHtml = `
            <div class="modal fade" id="editArticleModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-edit me-2"></i>
                                编辑文章
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <form id="edit-article-form">
                                <div class="mb-3">
                                    <label for="edit-article-title" class="form-label">标题</label>
                                    <input type="text" class="form-control" id="edit-article-title" 
                                           value="${article.title || ''}" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="edit-article-content" class="form-label">内容</label>
                                    <textarea class="form-control" id="edit-article-content" 
                                              rows="10" required>${article.content || ''}</textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="edit-article-tags" class="form-label">标签</label>
                                            <input type="text" class="form-control" id="edit-article-tags" 
                                                   value="${article.tags || ''}" 
                                                   placeholder="用逗号分隔">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="edit-article-cover" class="form-label">封面图片</label>
                                            <input type="text" class="form-control" id="edit-article-cover" 
                                                   value="${article.coverImage || ''}" 
                                                   placeholder="图片URL或路径">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="edit-article-summary" class="form-label">摘要</label>
                                    <textarea class="form-control" id="edit-article-summary" 
                                              rows="3">${article.summary || ''}</textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" 
                                                   id="edit-is-original" ${article.isOriginal ? 'checked' : ''}>
                                            <label class="form-check-label" for="edit-is-original">
                                                原创内容
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" 
                                                   id="edit-join-activity" ${article.joinActivity ? 'checked' : ''}>
                                            <label class="form-check-label" for="edit-join-activity">
                                                参与活动
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="app.updateArticle(${article.id})">
                                <i class="fas fa-save me-2"></i>保存修改
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除旧的模态框
        const existingModal = document.getElementById('editArticleModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加新的模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editArticleModal'));
        modal.show();
    }
    
    // 更新文章
    async updateArticle(id) {
        try {
            const title = document.getElementById('edit-article-title').value.trim();
            const content = document.getElementById('edit-article-content').value.trim();
            
            if (!title || !content) {
                this.showAlert('标题和内容不能为空', 'warning');
                return;
            }
            
            const updateData = {
                title: title,
                content: content,
                htmlContent: content, // 这里可以后续改为Markdown转换
                tags: document.getElementById('edit-article-tags').value.trim(),
                coverImage: document.getElementById('edit-article-cover').value.trim(),
                summary: document.getElementById('edit-article-summary').value.trim(),
                isOriginal: document.getElementById('edit-is-original').checked,
                joinActivity: document.getElementById('edit-join-activity').checked
            };
            
            const response = await fetch(`/api/articles/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updateData)
            });
            
            if (!response.ok) {
                throw new Error('更新文章失败');
            }
            
            this.showAlert('文章更新成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('editArticleModal'));
            modal.hide();
            
            // 刷新文章列表
            this.loadArticles();
            
        } catch (error) {
            console.error('更新文章失败:', error);
            this.showAlert('更新文章失败: ' + error.message, 'danger');
        }
    }
    
    async republishArticle(id) {
        try {
            const response = await fetch(`/api/articles/${id}/publish`, {
                method: 'POST'
            });
            
            if (!response.ok) {
                throw new Error('重新发布失败');
            }
            
            this.showAlert('重新发布任务已启动', 'success');
            
        } catch (error) {
            console.error('重新发布失败:', error);
            this.showAlert('重新发布失败: ' + error.message, 'danger');
        }
    }
    
    async deleteArticle(id) {
        if (!confirm('确定要删除这篇文章吗？')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/articles/${id}`, {
                method: 'DELETE'
            });
            
            if (!response.ok) {
                throw new Error('删除失败');
            }
            
            this.showAlert('文章删除成功', 'success');
            this.loadArticles();
            
        } catch (error) {
            console.error('删除文章失败:', error);
            this.showAlert('删除文章失败: ' + error.message, 'danger');
        }
    }
    
    // 视频操作方法
    editVideo(id) {
        this.showAlert('编辑功能开发中...', 'info');
    }
    
    async republishVideo(id) {
        try {
            const response = await fetch(`/api/videos/${id}/publish`, {
                method: 'POST'
            });
            
            if (!response.ok) {
                throw new Error('重新发布失败');
            }
            
            this.showAlert('重新发布任务已启动', 'success');
            
        } catch (error) {
            console.error('重新发布失败:', error);
            this.showAlert('重新发布失败: ' + error.message, 'danger');
        }
    }
    
    async deleteVideo(id) {
        if (!confirm('确定要删除这个视频吗？')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/videos/${id}`, {
                method: 'DELETE'
            });
            
            if (!response.ok) {
                throw new Error('删除失败');
            }
            
            this.showAlert('视频删除成功', 'success');
            this.loadVideos();
            
        } catch (error) {
            console.error('删除视频失败:', error);
            this.showAlert('删除视频失败: ' + error.message, 'danger');
        }
    }
    
    // 处理平台选择变化
    handlePlatformAuthChange(platformCode, platformId) {
        const toutiaoCookiesSection = document.getElementById('toutiao-cookies-section');
        const traditionalAuthSection = document.getElementById('traditional-auth-section');
        
        if (platformCode === 'toutiao') {
            // 显示头条cookies配置区域
            toutiaoCookiesSection.classList.remove('d-none');
            traditionalAuthSection.classList.add('d-none');
        } else {
            // 显示传统认证区域
            toutiaoCookiesSection.classList.add('d-none');
            traditionalAuthSection.classList.remove('d-none');
        }
        
        // 加载已有的认证信息
        if (platformCode && platformId) {
            this.loadExistingAuthInfo(platformCode, platformId);
        } else {
            // 清空表单
            this.clearAuthForm();
        }
    }
    
    // 设置头条cookies相关事件处理器
    setupToutiaoCookiesHandlers() {
        console.log('设置头条cookies事件处理器...');
        
        // 自动检测获取cookies按钮
        const detectBtn = document.getElementById('detect-toutiao-cookies-btn');
        console.log('查找自动获取按钮:', detectBtn);
        
        if (detectBtn) {
            console.log('找到自动获取按钮，绑定click事件');
            // 移除旧的事件监听器（如果有）
            detectBtn.removeEventListener('click', this.detectToutiaoCookiesHandler);
            
            // 创建绑定到this的处理器
            this.detectToutiaoCookiesHandler = () => {
                console.log('自动获取按钮被点击');
                this.detectToutiaoCookies();
            };
            
            detectBtn.addEventListener('click', this.detectToutiaoCookiesHandler);
            console.log('自动获取按钮事件绑定成功');
        } else {
            console.warn('未找到自动获取按钮：#detect-toutiao-cookies-btn');
        }
        
        // 验证cookies有效性按钮
        const validateBtn = document.getElementById('validate-cookies-btn');
        if (validateBtn) {
            validateBtn.addEventListener('click', () => {
                this.validateToutiaoCookies();
            });
        }
        
        // 查看手动获取指引
        const instructionLink = document.getElementById('show-cookies-instruction');
        if (instructionLink) {
            instructionLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.showToutiaoCookiesInstruction();
            });
        }
        
        // 使用手动输入的cookies
        const useManualBtn = document.getElementById('use-manual-cookies-btn');
        if (useManualBtn) {
            useManualBtn.addEventListener('click', () => {
                this.useManualCookies();
            });
        }
        
        // 验证手动输入的cookies
        const validateManualBtn = document.getElementById('validate-manual-cookies-btn');
        if (validateManualBtn) {
            validateManualBtn.addEventListener('click', () => {
                this.validateManualCookies();
            });
        }
    }
    
    // 自动检测获取头条cookies
    async detectToutiaoCookies() {
        console.log('开始自动检测头条cookies...');
        
        const btn = document.getElementById('detect-toutiao-cookies-btn');
        if (!btn) {
            console.error('找不到自动获取按钮');
            this.showAlert('按钮元素未找到', 'danger');
            return;
        }
        
        const originalText = btn.innerHTML;
        console.log('按钮原始文本:', originalText);
        
        try {
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 检测中...';
            btn.disabled = true;
            
            console.log('发送API请求到: /api/platforms/toutiao/detect-cookies');
            const response = await fetch('/api/platforms/toutiao/detect-cookies', {
                method: 'POST'
            });
            
            console.log('API响应状态:', response.status);
            const result = await response.json();
            console.log('API响应结果:', result);
            
            if (result.success) {
                // 成功获取cookies
                const cookiesTextarea = document.getElementById('auth-cookies-toutiao');
                if (cookiesTextarea) {
                    cookiesTextarea.value = result.cookies;
                    console.log('已将cookies填入文本框');
                } else {
                    console.error('找不到cookies文本框');
                }
                
                this.showAlert('成功获取头条cookies！', 'success');
                
                // 自动验证
                setTimeout(() => {
                    this.validateToutiaoCookies();
                }, 1000);
                
            } else {
                // 检测失败，显示指引
                console.warn('自动获取失败:', result.message);
                this.showAlert(result.message || '自动获取失败，请手动获取', 'warning');
                if (result.instruction) {
                    this.showToutiaoCookiesInstruction();
                }
            }
            
        } catch (error) {
            console.error('检测cookies失败:', error);
            this.showAlert('检测失败: ' + error.message, 'danger');
        } finally {
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    }
    
    // 验证头条cookies有效性
    async validateToutiaoCookies() {
        const cookiesTextarea = document.getElementById('auth-cookies-toutiao');
        const cookies = cookiesTextarea.value.trim();
        
        if (!cookies) {
            this.showAlert('请先输入cookies', 'warning');
            return;
        }
        
        const statusSpan = document.getElementById('cookies-validation-status');
        
        try {
            statusSpan.innerHTML = '<i class="fas fa-spinner fa-spin text-primary"></i> 验证中...';
            
            const response = await fetch('/api/platforms/toutiao/validate-cookies', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ cookies })
            });
            
            const result = await response.json();
            
            if (result.success && result.valid) {
                statusSpan.innerHTML = '<i class="fas fa-check-circle text-success"></i> Cookies有效';
                this.showAlert('Cookies验证成功！', 'success');
            } else {
                statusSpan.innerHTML = '<i class="fas fa-times-circle text-danger"></i> Cookies无效';
                this.showAlert(result.message || 'Cookies无效或已过期', 'danger');
            }
            
        } catch (error) {
            console.error('验证cookies失败:', error);
            statusSpan.innerHTML = '<i class="fas fa-exclamation-triangle text-warning"></i> 验证失败';
            this.showAlert('验证失败: ' + error.message, 'danger');
        }
    }
    
    // 显示头条cookies获取指引
    showToutiaoCookiesInstruction() {
        const modal = new bootstrap.Modal(document.getElementById('toutiaoCookiesModal'));
        modal.show();
    }
    
    // 使用手动输入的cookies
    useManualCookies() {
        const manualCookiesInput = document.getElementById('manual-cookies-input');
        const cookiesTextarea = document.getElementById('auth-cookies-toutiao');
        
        const cookies = manualCookiesInput.value.trim();
        if (!cookies) {
            this.showAlert('请先输入cookies', 'warning');
            return;
        }
        
        cookiesTextarea.value = cookies;
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('toutiaoCookiesModal'));
        if (modal) {
            modal.hide();
        }
        
        this.showAlert('已将cookies填入到配置框', 'success');
        
        // 自动验证
        setTimeout(() => {
            this.validateToutiaoCookies();
        }, 500);
    }
    
    // 验证手动输入的cookies
    async validateManualCookies() {
        const manualCookiesInput = document.getElementById('manual-cookies-input');
        const cookies = manualCookiesInput.value.trim();
        
        if (!cookies) {
            this.showAlert('请先输入cookies', 'warning');
            return;
        }
        
        try {
            const response = await fetch('/api/platforms/toutiao/validate-cookies', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ cookies })
            });
            
            const result = await response.json();
            
            if (result.success && result.valid) {
                this.showAlert('手动输入的Cookies有效！', 'success');
            } else {
                this.showAlert(result.message || '手动输入的Cookies无效', 'danger');
            }
            
        } catch (error) {
            console.error('验证手动cookies失败:', error);
            this.showAlert('验证失败: ' + error.message, 'danger');
        }
    }
    
    // 加载已有的认证信息
    async loadExistingAuthInfo(platformCode, platformId) {
        try {
            // 直接使用传入的platformId
            if (!platformId) {
                console.log('平台ID为空');
                return;
            }
            
            const response = await fetch(`/api/platforms/${platformId}/auth`);
            if (!response.ok) {
                console.log('获取认证信息失败');
                return;
            }
            
            const authList = await response.json();
            console.log('加载到的认证信息:', authList);
            
            if (authList && authList.length > 0) {
                const auth = authList[0]; // 取第一个认证信息
                
                // 填充用户标识
                const userIdentifierField = document.getElementById('auth-user');
                if (userIdentifierField && auth.userIdentifier) {
                    userIdentifierField.value = auth.userIdentifier;
                }
                
                if (platformCode === 'toutiao') {
                    // 头条平台填充cookies
                    const cookiesField = document.getElementById('auth-cookies-toutiao');
                    if (cookiesField && auth.cookies) {
                        cookiesField.value = auth.cookies;
                        // 自动验证cookies
                        setTimeout(() => {
                            this.validateToutiaoCookies();
                        }, 500);
                    }
                } else {
                    // 其他平台填充token和cookies
                    const tokenField = document.getElementById('auth-token');
                    const cookiesField = document.getElementById('auth-cookies');
                    
                    if (tokenField && auth.accessToken) {
                        tokenField.value = auth.accessToken;
                    }
                    
                    if (cookiesField && auth.cookies) {
                        cookiesField.value = auth.cookies;
                    }
                }
                
                console.log('认证信息已加载到表单');
            }
            
        } catch (error) {
            console.error('加载认证信息失败:', error);
        }
    }
    
    // 清空认证表单
    clearAuthForm() {
        // 清空所有输入框
        const userField = document.getElementById('auth-user');
        const tokenField = document.getElementById('auth-token');
        const cookiesField = document.getElementById('auth-cookies');
        const toutiaoCookiesField = document.getElementById('auth-cookies-toutiao');
        const validationStatus = document.getElementById('cookies-validation-status');
        
        if (userField) userField.value = '';
        if (tokenField) tokenField.value = '';
        if (cookiesField) cookiesField.value = '';
        if (toutiaoCookiesField) toutiaoCookiesField.value = '';
        if (validationStatus) validationStatus.innerHTML = '';
    }
}

// 初始化应用
const app = new ArticleSyncApp();